import { isArray } from './prototype.js'

/**
 * 判断参数是否是其中之一  includes ?
 * @param {*} value
 * @param {*} validList
 * @returns
 */
export function oneOf (value, validList) {
  if (!isArray(validList)) {
    throw new TypeError('args[1] must a array')
  }
  for (let i = 0; i < validList.length; i++) {
    if (value === validList[i]) {
      return true
    }
  }
  return false
}

/**
 * 枚举转换对象数据
 * @param {*} arr  枚举列表
 * @param {*} fmtLabel
 * @param {*} fmtValue
 * @returns
 */
 export function dataProvider (arr, fmtLabel = 'label', fmtValue = 'value') {
  let obj = {}
  if (isArray(arr)) {
    throw new TypeError('args[0] must a array')
  }
  arr.forEach(r => {
    obj[r[fmtValue]] = r[fmtLabel]
  })
  return obj
}

/**
 * 创建一个长度数组
 * @param {*} num 长度
 * @returns
 */
export function createArr (num) {
  let i = -1
  const arr = []
  while (++i < num) {
    arr.push(i)
  }
  return arr
}

export function listToTree (list, id, pid, children) {
  const map = {}
  list.forEach(item => {
    map[item[id]] = item
  })
  const tree = []
  list.forEach(item => {
    const parent = map[item[pid]]
    if (parent) {
      (parent[children] || (parent[children] = [])).push(item)
    } else {
      tree.push(item)
    }
  })
  return tree
}

export function treeToList (tree, child, field) {
  const arr = []
  if (isArray(tree)) {
    tree.forEach((item, idx) => {
      if (item.level) {
        if (item.level === 2) {
          item[field] = tree.length === idx + 1 ? `  └─ ${item[field]}` : `  ├─ ${item[field]}`
        } else if (item.level === 3) {
          item[field] = tree.length === idx + 1 ? `  │  └─ ${item[field]}` : `  │  ├─ ${item[field]}`
        }
      }
      arr.push(item)
      if (item[child] && item[child].length) arr.push(...treeToList(item[child], child, field))
    })
  }
  return arr
}
